package com.ncloud.crm.service.impl;

import java.util.List;

import com.ncloud.param.service.SequenceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.order.OrderAccount;
import com.ncloud.crm.mapper.OrderAccountMapper;
import com.ncloud.crm.service.OrderAccountService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;

@Service
public class OrderAccountServiceImpl implements OrderAccountService {
	
	private static final Logger logger = LogManager.getLogger(OrderAccountServiceImpl.class);
	
	@Autowired
	private OrderAccountMapper orderAccountMapper;
	@Reference
	private SequenceService sequenceService;


	public List<OrderAccount> getByOrderId(Long orderId){
		List<OrderAccount> orderAccounts = orderAccountMapper.getAccountByOrderId(orderId);
		return orderAccounts;
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject insert(JSONObject json) {

		OrderAccount orderAccount = JSON.parseObject(json.toJSONString(),OrderAccount.class);
		try {
			validation(orderAccount);
			orderAccountMapper.insertOrderAccount(orderAccount);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}

	@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject jsonObject = new JSONObject();
		if(json == null){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		if(json.containsKey(OrderNodeDefineUtils.ORDER_ACCOUNT)){
			jsonObject = validateInner(json,result);
		}else{
			if(json.containsKey(OrderNodeDefineUtils.ORDER_CUSTOMER) ){
				JSONObject customer =json.getJSONObject(OrderNodeDefineUtils.ORDER_CUSTOMER);
				String modifyTag = customer.getString("modifyTag");
				if(StringUtils.isEmpty(modifyTag)){
					throw new UserException(ResultEnum.PARAM_ERROR);
				}
			/*依赖于客户信息，客户已经存在，账户也不需要处理，这里根据动作判断存在*/
				if(modifyTag.equals(Constant.ADD)){
					OrderAccount orderAccount = new OrderAccount();
					orderAccount.setOrderId(result.getLong("orderId"));
					Long id = sequenceService.getSequence("seq_account_id");
					orderAccount.setAcctId(id);
					//缓存当前账户id
					result.put(TableIdDefineUtils.ACCOUNT_ID,id);
					orderAccount.setModifyTag("1");
					orderAccount.setCustId(result.getLong("custId"));
					orderAccount.setCreateTime(DateUtils.getDateTime());
					orderAccount.setCreateUser(json.getLong("userId"));
					orderAccount.setAcctName(customer.containsKey("custName")?customer.getString("custName"):"测试");
					jsonObject = JSON.parseObject(JSON.toJSONString(orderAccount));
					//json.put(OrderNodeDefineUtils.ORDER_ACCOUNT,JSON.parseObject(JSON.toJSONString(orderAccount)));
				}
			}
		}
		logger.info("订单账户信息:{}"+jsonObject.toJSONString());
		return jsonObject;
	}

	private JSONObject validateInner(JSONObject json,JSONObject result){
		JSONObject jsonObject = json.getJSONObject(OrderNodeDefineUtils.ORDER_ACCOUNT);
		String modifyTag = jsonObject.getString("modifyTag");
		if(StringUtils.isEmpty(modifyTag)){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
			/*生成accountId*/
		if(!jsonObject.containsKey(TableIdDefineUtils.ACCOUNT_ID) || StringUtils.isEmpty(jsonObject.getString(TableIdDefineUtils.ACCOUNT_ID))){
			Long id = sequenceService.getSequence("seq_account_id");
			jsonObject.put(TableIdDefineUtils.ACCOUNT_ID,id);
			result.put(TableIdDefineUtils.ACCOUNT_ID,id);
		}
			/*生成orderId*/
		if(!jsonObject.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(jsonObject.getString(TableIdDefineUtils.ORDER_ID))) {
			if (!result.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.ORDER_ID))) {
				throw new UserException(ResultEnum.PARAM_ERROR.getCode(), "订单账户信息orderId不存在！");
			} else {
				jsonObject.put(TableIdDefineUtils.ORDER_ID, result.getString(TableIdDefineUtils.ORDER_ID));
			}
		}
			/*处理custId*/
		if(!jsonObject.containsKey(TableIdDefineUtils.CUST_ID) || StringUtils.isEmpty(jsonObject.getString(TableIdDefineUtils.CUST_ID))){
			if(modifyTag.equals("1")){
				if(!result.containsKey(TableIdDefineUtils.CUST_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.CUST_ID))){
					throw new UserException(ResultEnum.PARAM_ERROR.getCode(), "订单账户信息custId不存在！");
				}else{
					jsonObject.put(TableIdDefineUtils.CUST_ID,result.getString(TableIdDefineUtils.CUST_ID));
				}
			}else{
				throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"订单账户信息custId不存在！");
			}
		}
		if(result.containsKey("custName")){
			jsonObject.put("custName",result.getString("custName"));
		}else {
			jsonObject.put("custName","");
		}
		//设置人员
		jsonObject.put("createUser",json.getLong("userId"));
		//设置创建时间
		jsonObject.put("createTime", result.getString("createTime")!=null?result.getString("createTime"): DateUtils.getDateTime());
		return jsonObject;
	}


	private void validation(OrderAccount account){
		if(account.getAcctId() == null ){
			Long id = sequenceService.getSequence("seq_account_id");
			account.setAcctId(id);
		}

	}
}
